<?php
/**
 * Created by PhpStorm.
 * User: XT
 * Date: 2017/4/21
 * Time: 9:54
 */

namespace core\session\driver;

use core\session\SessionInterface;
use core\DB;

/**
 * Class DbSession
 * @package core\session
 */

class DbSession extends SessionInterface {

    public function __construct($db = '')
    {
        DB::connect($db);
    }

    public function open($savePath, $sessionName)
    {
        return true;
    }

    public function close()
    {
        return true;
    }

    /**
     * 读取session
     * @param $id
     * @return string
     */
    public function read($id)
    {
        return (string)(DB::table('sessions')->where('sid', '=', $id)->value('value'));
    }

    /**
     * 写入session
     * @param $id
     * @param $data
     * @return bool
     */
    public function write($id, $data)
    {
        $exist = (string)(DB::table('sessions')->where('sid', '=', $id)->value('sid'));
        if ($exist) {
            DB::table('sessions')->where('sid', '=', $id)->update(['value' => $data]);
        } else {
            DB::table('sessions')->insert(['value' => $data, 'sid' => $id]);
        }
        return true;
    }

    /**
     * 清除session
     * @param $id
     * @return bool
     */
    public function destroy($id)
    {
        DB::table('sessions')->where('sid', '=', $id)->delete();
        return true;
    }

    /**
     * 工厂回收
     * @param $maxLifeTime
     * @return bool
     */
    public function gc($maxLifeTime)
    {
        DB::table('sessions')->where('expire', '>', " FROM_UNIXTIME(UNIX_TIMESTAMP(expire) + $maxLifeTime ) ")->delete();

        return true;
    }
}